package io.renren.modules.study.service.impl;


import io.renren.common.config.RedisProperies;
import io.renren.modules.study.dao.CourseDao;
import io.renren.modules.study.dao.MyCourseDao;
import io.renren.modules.study.entity.*;
import io.renren.modules.sys.dto.CollectDto;
import io.renren.modules.sys.dto.TeacherAndCourseMustKnow;
import io.renren.modules.sys.entity.*;
import io.renren.modules.study.service.CourseService;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("courseService")
public class CourseServiceImpl  implements CourseService {

    @Autowired
    CourseDao courseDao;
    @Autowired
    MyCourseDao myCourseDao;

    @Override
    public List getCourseList(Map<String, Object> params) {
        return courseDao.selectList(params);
    }

    @Override
    public PcPageBean<Course> getAllCourseByOnce(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<Course> allCourse = courseDao.getAllCourseByOnce(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.getAllCourseByOnce(params));
        return pb;
    }

    @Override
    public PcPageBean<Course> getCourseAndTeacherName(Map<String, Object> params) {
        int pageNum = (int) params.get("pageNum");
        int pageSize = (int) params.get("pageSize");
        List<Course> allCourse = courseDao.getAllCourse(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.getCourseAndTeacherName(params));
        return pb;
    }


    @Override
    public PcPageBean<CourseComment> getCourseCommentByCourseIdPc(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<CourseComment> allCourse = courseDao.getCourseCommentByCourseIdPc(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.getCourseCommentByCourseIdPc(params));
        return pb;
    }

    @Override
    public PcPageBean<Course> pcGetMyCollectionCouseList(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<CourseComment> allCourse = courseDao.pcGetMyCollectionCouseList(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.pcGetMyCollectionCouseList(params));
        return pb;
    }
    @Override
    public PcPageBean<Course> pcGetMyLearnCouseList(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<CourseComment> allCourse = courseDao.pcGetMyLearnCouseList(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.pcGetMyLearnCouseList(params));
        return pb;
    }

    @Override
    public PcPageBean<CourseComment> pcGetCourseCommentByUserId(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<CourseComment> allCourse = courseDao.pcGetCourseCommentByUserId(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.pcGetCourseCommentByUserId(params));
        return pb;
    }

    @Override
    public PcPageBean<Course> pcGetCourseByTitleLike(Map<String, Object> params) {
        int pageNum = (int)params.get("pageNum");
        int pageSize = (int)params.get("pageSize");
        List<Course> allCourse = courseDao.pcGetCourseByTitleLike(params);
        int totalRecord = allCourse.size();
        PcPageBean pb = new PcPageBean(pageNum,pageSize,totalRecord);
        int startIndex = pb.getStartIndex();
        params.put("startIndex",startIndex);
        pb.setList(courseDao.pcGetCourseByTitleLike(params));
        return pb;
    }


    @Override
    public Map getsearchData() {
        Map map=new HashMap();
        List<Direction> directionList=courseDao.getDirectionList();
        List<Classification> classificationList=courseDao.getClassificationList();
        map.put("direction",directionList);
        map.put("classification",classificationList);
        return map;
    }

    @Override
    public Course getCourseById(Integer id) {
        List<CourseBody> courseBodyList=courseDao.getCourseBodyListByCourseId(id);
        for(CourseBody courseBody:courseBodyList) {
            if(courseBody.getVideoPath()!= null && !"".equals(courseBody.getVideoPath())){
                String vodeoPath = checkHttp(courseBody.getVideoPath());
                courseBody.setVideoPath(vodeoPath);
            }
            if(null != courseBody.getCoverPath() && !"".equals(courseBody.getCoverPath())){
                String coverPath = checkHttp(courseBody.getCoverPath());
                courseBody.setCoverPath(coverPath);
            }
              if(null != courseBody.getDataPath() && !"".equals(courseBody.getDataPath()))  {
                  String dataPath = checkHttp(courseBody.getDataPath());
                  courseBody.setDataPath(dataPath);
              }
                if(null != courseBody.getVideoHdPath() && !"".equals(courseBody.getVideoHdPath())){
                    String videoHdPath = checkHttp(courseBody.getVideoHdPath());
                    courseBody.setVideoHdPath(videoHdPath);
                }
        }
        Course course=courseDao.getCoureById(id);
        setCourse(course,courseBodyList);
        return course;
    }

    @Override
    public Course getCourseById(Integer id,Integer userId) {

        Map map=new HashMap();
        map.put("courseId",id);
        map.put("userId",userId);
        //Jedis jedis=new Jedis("106.14.146.131");
        //jedis.flushAll();  //删除其中的数据
        //CourseScheduleEntity courseScheduleEntity=null;
        Course course=null;
        List<CourseBody> courseBodyList=null;
        //String jsonStr= jedis.get("courseId"+id.toString());
        //JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
        //JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"MM-dd-yyyy HH:mm:ss"}) );
       // course = (Course)JSONObject.toBean(obj,Course.class);//将建json对象转换为Person对象

        if(course==null) {
                course = courseDao.getCoureById(id);
                courseBodyList=courseDao.getCourseBodyListByCourseId(id);


            //JSONObject json = JSONObject.fromObject(course);//将java对象转换为json对象
            //String str = json.toString();//将json对象转换为字符串

            //JSONArray jsonarray = JSONArray.fromObject(courseBodyList);
            //jedis.set("courseId"+id.toString(), str);
            //jedis.set("courseBody"+id.toString(), jsonarray.toString());

        }else{
            //JSONArray array = JSONArray.fromObject(jedis.get("courseBody"+id.toString()));
           // courseBodyList = JSONArray.toList(array, CourseBody.class);// 过时方法
        }

        CourseScheduleEntity courseScheduleEntity = myCourseDao.getMCoursechedule(map);

        for(CourseBody courseBody:courseBodyList) {
            if(courseBody.getVideoPath()!= null && !"".equals(courseBody.getVideoPath())){
                String vodeoPath = checkHttp(courseBody.getVideoPath());
                courseBody.setVideoPath(vodeoPath);
            }
            if(null != courseBody.getCoverPath() && !"".equals(courseBody.getCoverPath())){
                String coverPath = checkHttp(courseBody.getCoverPath());
                courseBody.setCoverPath(coverPath);
            }
            if(null != courseBody.getDataPath() && !"".equals(courseBody.getDataPath()))  {
                String dataPath = checkHttp(courseBody.getDataPath());
                courseBody.setDataPath(dataPath);
            }
            if(null != courseBody.getVideoHdPath() && !"".equals(courseBody.getVideoHdPath())){
                String videoHdPath = checkHttp(courseBody.getVideoHdPath());
                courseBody.setVideoHdPath(videoHdPath);
            }

            if(courseScheduleEntity!=null){
                if(null!=courseScheduleEntity.getCourseBodyId()&&courseScheduleEntity.getCourseBodyId()==courseBody.getId()){
                    courseBody.setIslastLoading(1);
                    courseBody.setVideoSchedule(courseScheduleEntity.getCourseBodyTime());
                }
            }

           /*if(userId != null && !"".equals(userId.toString())){
               CourseScheduleEntity courseScheduleEntity = myCourseDao.getMCoursechedule(map);

               if(courseScheduleEntity!=null){
                   if(null!=courseScheduleEntity.getCourseBodyId()&&courseScheduleEntity.getCourseBodyId()==courseBody.getId()){
                       courseBody.setIslastLoading(1);
                       courseBody.setVideoSchedule(courseScheduleEntity.getCourseBodyTime());
                   }
               }
           }*/
        }

        setCourse(course,courseBodyList);
        return course;
    }


    /**
     * 判断https://是否存在
     */
    public String checkHttp(String path){

            String p = path.substring(0,4);
            if(!"http".equals(p)){
                StringBuffer stringBuilder1=new StringBuffer(path);
                stringBuilder1.insert(0,"https://");
                String newPath = stringBuilder1.toString();
                return newPath;
            }else{
                return path;
            }
    }

    /**
     * 增加当前课程的收藏数量
     * @param course
     * @return
     */
    @Override
    public int addCourseCount(CollectDto course) {
        return courseDao.addCourseCount(course);
    }

    /**
     * 减少当前课程收藏数量
     * @param course
     * @return
     */
    @Override
    public int delCourseCount(CollectDto course) {
        return courseDao.delCourseCount(course);
    }

    /**
     * 添加我的收藏课程到关系表中
     * @param course
     */
    @Override
    public void addCollectionCourse(CollectDto course) {
        courseDao.addCollectionCourse(course);
    }

    /**
     * 在关系表中修改我的收藏课程的关系
     * @param course
     */
    @Override
    public void delCollectionCourse(CollectDto course) {
        courseDao.delCollectionCourse(course);
    }

    /**
     * 查看我的收藏列表
     * @return
     */
    @Override
    public List getMyCollectionCouseList(CollectDto collectDto) {
        return courseDao.getMyCollectionCouseList(collectDto);
    }

    /**
     * 查看当前收藏的课程
     * @param collectDto
     * @return
     */
    @Override
    public List getMyCollectionCouse(CollectDto collectDto) {
        return courseDao.getMyCollectionCouse(collectDto);
    }

    /**
     * 查询当前课程的讲师的信息和课程须知
     * @param course
     * @return
     */
    @Override
    public TeacherAndCourseMustKnow getTeacherAndCourseMustKnow(Course course) {
        return courseDao.getTeacherAndCourseMustKnow(course);
    }

    /**
     * 查看当前课程是否被当前用户收藏
     * @param collectDto
     * @return
     */
    @Override
    public List checkIsCollection(CollectDto collectDto) {
        return courseDao.checkIsCollection(collectDto);
    }

    @Override
    public List getCourseByTitleLike(Map map) {
        return courseDao.getCourseByTitleLike(map);
    }

    @Override
    public void saveCourseComment(CourseComment courseComment) {
        courseDao.saveCourseComment(courseComment);
    }

    @Override
    public void delCourseComment(CourseComment courseComment) {
        courseDao.delCourseComment(courseComment);
    }

    @Override
    public List getCourseComment(Map map) {
        return courseDao.getCourseComment(map);
    }
    @Override
    public List getCourseCommentByUserId(Map map){
        return courseDao.getCourseCommentByUserId(map);
    }
    @Override
    public CourseComment getUserComment(CourseComment courseComment) {
        return courseDao.getUserComment(courseComment);
    }

    @Override
    public CourseClassification getClassificationChild(int parentId) {
        return courseDao.getClassificationChild(parentId);
    }

    @Override
    public List getClassification(Integer parentId) {
        return courseDao.getClassification(parentId);
    }

    @Override
    public List getFirstClassification() {
        return courseDao.getFirstClassification();
    }

    @Override
    public List getCourses(Map map) {
        return courseDao.getCourses(map);
    }

    @Override
    public int getClassificationIdByName(Map map) {
        return courseDao.getClassificationIdByName(map);
    }

    @Override
    public List courseListByHot(Map map) {
        return courseDao.courseListByHot(map);
    }

    @Override
    public List courseListByTime(Map map) {
        return courseDao.courseListByTime(map);
    }

    @Override
    public List courseListByHotDesc(Map map) {
        return courseDao.courseListByHotDesc(map);
    }

    @Override
    public List<Course> courseListByTimeDesc(Map map) {
        return courseDao.courseListByTimeDesc(map);
    }

    @Override
    public List<Course> courseListByPrice(Map map) {
        return courseDao.courseListByPrice(map);
    }

    @Override
    public List<Course> courseListByPriceDesc(Map map) {
        return courseDao.courseListByPriceDesc(map);
    }

    @Override
    public List<Course> getFirstCourseListByHot(Map map) {
        return courseDao.getFirstCourseListByHot(map);
    }

    @Override
    public List<Course> getFirstCourseListByHotDesc(Map map) {
        return courseDao.getFirstCourseListByHotDesc(map);
    }

    @Override
    public List<Course> getFirstCourseListByTime(Map map) {
        return courseDao.getFirstCourseListByTime(map);
    }

    @Override
    public List<Course> getFirstCourseListByTimeDesc(Map map) {
        return courseDao.getFirstCourseListByTimeDesc(map);
    }

    @Override
    public List<Course> getFirstcourseListByPrice(Map map) {
        return courseDao.getFirstcourseListByPrice(map);
    }

    @Override
    public List<Course> getFirstcourseListByPriceDesc(Map map) {
        return courseDao.getFirstcourseListByPriceDesc(map);
    }

    @Override
    public void addOrderInfo(UserCourseBuyHistory userCourseBuyHistory) {
        courseDao.addOrderInfo(userCourseBuyHistory);
    }

    @Override
    public List getLearnBannerData() {


        return courseDao.getLearnBannerData();
    }

    @Override
    public CourseBody getCourseBodyById(Map map) {
        return courseDao.getCourseBodyById(map);
    }

    @Override
    public void feedBack(Map map) {
        courseDao.feedBack(map);
    }

    @Override
    public int getCourseCount() {
        return courseDao.getCourseCount();
    }

    @Override
    public List getAllCourse() {
        List courseList = courseDao.getCourseRecommend();
        return courseList;
    }

    @Override
    public List getCourseIdList() {

        return courseDao.getCourseIdList();
    }

    @Override
    public List getDricationList() {
        return courseDao.getDricationList();
    }

    @Override
    public List getCourseIdByDirectionId(int directionId) {
        return courseDao.getCourseIdByDirectionId(directionId);
    }

    @Override
    public Course getCoursesNameAndOther(int oneDriectionCourseId) {
        return courseDao.getCoursesNameAndOther(oneDriectionCourseId);
    }

    private void setCourse(Course course, List<CourseBody> courseBodyList) {
        List<CourseBody> courseChildList= new ArrayList();
        for(CourseBody c:courseBodyList) {
            if(c.getParentId()==0||c.getParentId()==-1) {
                courseChildList.add(c);
                setCourseBody(c,courseBodyList);
            }
        }
        if(courseChildList.size()==0){
            courseChildList=null;
        }
        course.setChildBody(courseChildList);
    }

    private void setCourseBody(CourseBody courseBody,List<CourseBody> courseBodyList) {
        List<CourseBody> courseChildList= new ArrayList();
        for(CourseBody c:courseBodyList) {
            if(courseBody.getId()==c.getParentId()) {
                courseChildList.add(c);
                setCourseBody(c,courseBodyList);
            }
        }
        if (courseChildList.size()==0){
            courseChildList=null;
        }
        courseBody.setChildBody(courseChildList);
    }

}
